Shader "Hidden/Fullscreen/DownSample"
{
    HLSLINCLUDE

    #pragma vertex Vert

    #pragma target 4.5
    #pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

    #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl"

    TEXTURE2D_X(_Source);
    float4 _Offset;
    float4 _ViewportSize;
    float4 _Size;
    float _SceneViewMode;

    float4 DownSampleBoxBlur(Varyings varyings) : SV_Target
    {
        UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(varyings);
        
        // 为Scene视图优化UV计算
        float2 uv = varyings.positionCS.xy * _ScreenSize.zw;
        if (_SceneViewMode < 0.5) // Game视图
        {
            uv = uv * pow(2, _Size.x + 2); //前面取阈值已经缩小过了，这里多缩小一倍
        }
        else // Scene视图
        {
            uv = uv * _RTHandleScale.xy * pow(2, _Size.x + 2);
        }
        
        // 2x2盒式模糊 - 采样4个角点并取平均
        float4 color = float4(0, 0, 0, 0);
        
        // 左上角
        color += SAMPLE_TEXTURE2D_X_LOD(_Source, s_linear_clamp_sampler, uv + float2(-0.5 * _Offset.x, 0.5 * _Offset.y), 0);
        // 左下角  
        color += SAMPLE_TEXTURE2D_X_LOD(_Source, s_linear_clamp_sampler, uv + float2(-0.5 * _Offset.x, -0.5 * _Offset.y), 0);
        // 右上角
        color += SAMPLE_TEXTURE2D_X_LOD(_Source, s_linear_clamp_sampler, uv + float2(0.5 * _Offset.x, -0.5 * _Offset.y), 0);
        // 右下角
        color += SAMPLE_TEXTURE2D_X_LOD(_Source, s_linear_clamp_sampler, uv + float2(0.5 * _Offset.x, 0.5 * _Offset.y), 0);
        
        // 除以4取平均值（对应原始代码的0.25系数）
        color *= 0.25;

        return color;
    }

    ENDHLSL

    SubShader
    {
        Pass
        {
            Name "DownSample BoxBlur"

            ZWrite Off
            ZTest Always
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment DownSampleBoxBlur
            ENDHLSL
        }
    }
    Fallback Off
} 